import $ from 'jquery';
import {ElNotification} from 'element-plus'
import CryptoJS from 'crypto-js';

let SEVER_URL = "";

// 提交备份接口
export function backup(backupData: string) {
  let backUpConfig = JSON.parse(localStorage.getItem('backUpConfig')?.toString() ?? '{}');
  console.log("backUpConfig", JSON.stringify(backUpConfig) == '{}')
  if (JSON.stringify(backUpConfig) == '{}') {
    ElNotification({
      showClose: true,
      message: "请先配置备份服务器地址",
      offset: 80,
      duration: 1600,
      type: `error`,
    })
    return
  }

  SEVER_URL = backUpConfig.serverUrl;

  const formData = new FormData();
  formData.append('account', backUpConfig.account);
  formData.append('password', encrypt(backUpConfig.password.trim()));
  formData.append('isAdmin', "true");

  $.ajax({
    url: SEVER_URL + "/user/login",
    type: "POST",
    data: formData,
    processData: false, // 不对数据进行处理
    contentType: false, // 不设置 Content-Type
    success: function (data) {
      let message = data.message;
      let type = `success`;
      if (data.code != "200") {
        message = "登录失败：" + message;
        type = `error`;
      }
      backupArticle(data.data.accessToken, backupData)
    },
    error: function (xhr, status, error) {
      console.error("登录失败：", error);
    }
  });

}

function backupArticle(backupToken: string, backupData: string) {
  const backupUrl = SEVER_URL + "/article/saveArticle"

  $.ajax({
    url: backupUrl,
    type: "POST",
    data: backupData,
    headers: {
      "Content-Type": "application/json",
      "Authorization": backupToken,
    },
    success: function (data) {
      let message = "备份成功";
      let type = `success`;
      if (data.code != "200") {
        message = "备份失败：" + data.message;
        type = `error`;
      }

      // 输出提示
      ElNotification({
        showClose: true,
        message: message,
        offset: 80,
        duration: 1600,
        type: type,
      })
    },
    error: function (xhr, status, error) {
      console.error("备份失败：", error);
      // 输出提示
      ElNotification({
        showClose: true,
        message: "备份失败：" + error,
        offset: 80,
        duration: 1600,
        type: `error`,
      })
    }
  });
}

/**
 * 加密
 */
function encrypt(plaintText: string) {
  let options = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  };
  let key = CryptoJS.enc.Utf8.parse("sarasarasarasara");
  let encryptedData = CryptoJS.AES.encrypt(plaintText, key, options);
  return encryptedData.toString().replace(/\//g, "_").replace(/\+/g, "-");
}


